﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Aliyun
{
    /// <summary>
    /// 行为验证码校验过滤器
    /// </summary>
    public class BehaviorCaptchaFilter : ActionFilterAttribute
    {
        private readonly IBehaviorCaptcha verification;
        /// <summary>
        /// 行为验证码校验过滤器
        /// </summary>
        /// <param name="verification"></param>
        public BehaviorCaptchaFilter(IBehaviorCaptcha verification)
        {
            this.verification = verification;
        }
        /// <inheritdoc/>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string captcha = context.HttpContext.Request.Headers["captcha"];
            string captchaId = context.HttpContext.Request.Headers["captcha-id"];
            bool needCaptcha = context.ActionDescriptor.EndpointMetadata.OfType<CaptchaAttribute>().Any();
            if (string.IsNullOrEmpty(captcha) && string.IsNullOrEmpty(captchaId) && needCaptcha)
            {
                context.Result = new ObjectResult(FuncResult.Fail("请先完成人机验证", "0400"));
                return;
            }
            if (string.IsNullOrEmpty(captcha) && string.IsNullOrEmpty(captchaId))
            {
                return;
            }
            var result = this.verification.Verify(captchaId, captcha);
            if (!result)
            {
                context.Result = new ObjectResult(FuncResult.Fail(result?.Message ?? "人机验证未通过", "0400"));
            }
        }
    }
}
